<?php

class requestsActions extends sfActions {

    public function executeIndex(sfWebRequest $request) {
        try {
            $this->addCalendar($request);

            $this->calendarRequests = RequestRestResource::singleton()->searchByUserId($this->getUser()->getId(), $this->from, $this->to);
            $this->requests = RequestRestResource::singleton()->findAllByUserId($this->getUser()->getId());
            $this->requestTypes = RequestTypeRestResource::singleton()->findAllAndMap('id', 'description');
        } catch (YougoException $e) {
            $this->getUser()->setFlashGlobalError();
        }
    }

    public function executeNew(sfWebRequest $request) {
        $this->form = new RequestForm(null, array('mode' => 'new'));
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new RequestForm();

        $this->processFormCreate($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        try {
            $_request = RequestRestResource::singleton()->findByUserId($this->getUser()->getId(), $request->getParameter('id'));
            $this->form = new RequestForm($_request, array('mode' => 'edit'));
        } catch (YougoException $e) {
            $this->getUser()->setFlashError();
            $this->redirect('users/index');
        }
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));

        try {
            $_request = RequestRestResource::singleton()->findByUserId($this->getUser()->getId(), $request->getParameter('id'));
            $this->form = new RequestForm($_request, array('mode' => 'edit'));
        } catch (YougoException $e) {
            $this->getUser()->setFlashError();
        }

        $this->processFormUpdate($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        try {
            RequestRestResource::singleton()->deleteByUserId($this->getUser()->getId(), $request->getParameter('id'));
            $this->form = new UserForm($user);
            $this->getUser()->setFlash('notice', 'Request deleted successfully.');
        } catch (YougoException $e) {
            $this->getUser()->setFlashError();
        }

        $this->redirect('requests/index');
    }

    public function executeValidation(sfWebRequest $request) {
        $this->addCalendar($request);

        $this->form = new RequestStatusFormFilter(array('requestStatus' => $this->getUser()->getAttribute('requestStatus')));

        if ($request->getMethod() == sfRequest::POST) {
            $this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
            if ($this->form->isValid()) {
                $this->getUser()->setAttribute('requestStatus', $this->form->getValue('requestStatus'));
            }
        }

        try {
            $this->detailedUsers = DetailedUserRestResource::singleton()->search($this->from, $this->to, $this->getUser()->getAttribute('requestStatus'));
            $this->requestTypes = RequestTypeRestResource::singleton()->findAllAndMap('id', 'description');
        } catch (YougoException $e) {
            $this->getUser()->setFlashGlobalError();
        }
    }

    public function executeValidate(sfWebRequest $request) {
        try {
            $_request = RequestRestResource::singleton()->findByUserId($request->getParameter('userId'), $request->getParameter('id'));
            $this->form = new RequestForm($_request, array('mode' => 'validate'));
        } catch (YougoException $e) {
            $this->getUser()->setFlashError();
        }

        if ($request->isXmlHttpRequest())
            $this->setLayout('ajaxLayout');

        $this->userId = $request->getParameter('userId');
    }

    public function executeUpdateValidation(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));

        try {
            $_request = RequestRestResource::singleton()->findByUserId($request->getParameter('userId'), $request->getParameter('id'));
            $this->form = new RequestForm($_request, array('mode' => 'validate'));
        } catch (YougoException $e) {
            $this->getUser()->setFlashError();
        }

        $formOk = $this->processFormUpdateValidation($request, $this->form);
        if ($request->isXmlHttpRequest()) {
            if ($formOk === true) {
                $this->getResponse()->setContentType('application/json');
                $json = json_encode(array(
                            'response' => 'OK',
                            'id' => $this->values['id'],
                            'status' => $this->values['status'],
                            'flashNotice' => $this->getContext()->getI18N()->__($this->getUser()->getFlash('notice'))));
                $this->getUser()->setFlash('notice', '');
                return $this->renderText($json);
            }
            if ($formOk === false) {
                $this->getResponse()->setContentType('application/json');
                $json = json_encode(array(
                            'response' => 'NOK',
                            'flashError' => $this->getContext()->getI18N()->__($this->getUser()->getFlash('error'))));
                $this->getUser()->setFlash('error', '');
                return $this->renderText($json);
            }
            $this->setLayout('ajaxLayout');
        }

        $this->userId = $request->getParameter('userId');

        $this->setTemplate('validate');
    }

    protected function addCalendar(sfWebRequest $request) {
        $this->from = new DateTime();

        // Gestion des paramètres de pagination
        if ($request->getParameter('page') != null) {
            $shit = $request->getParameter('page') * floor(sfConfig::get('app_calendar_size') / 2);
            $this->from->modify($shit . ' day');
            $this->page = $request->getParameter('page');
        } else {
            $this->page = 0;
        }

        $this->to = clone $this->from;
        $this->to->modify('+' . sfConfig::get('app_calendar_size') . ' day')->modify('-1 day');
        $this->calendar = Calendar::create($this->from, $this->to);
    }

    protected function processFormCreate(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            try {
                $id = RequestRestResource::singleton()->createByUserId($this->getUser()->getId(), $form->getValues());
                $this->getUser()->setFlash('notice', 'Request created successfully.');
                $this->redirect('requests/index');
            } catch (YougoException $e) {
                $this->getUser()->setFlashError();
            }
        }
    }

    protected function processFormUpdate(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            try {
                RequestRestResource::singleton()->updateByUserId($this->getUser()->getId(), $form->getValues());
                $_request = RequestRestResource::singleton()->findByUserId($this->getUser()->getId(), $form->getValue('id'));
                $this->getUser()->setFlash('notice', 'Request updated successfully.');
                $this->redirect('requests/edit?id=' . $_request->id);
            } catch (YougoException $e) {
                $this->getUser()->setFlashError();
            }
        }
    }

    protected function processFormUpdateValidation(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $values = $form->getValues();
            $values['status'] = $request->hasParameter('_accept') ? 'ACCEPTED' : 'REFUSED';
            $this->values = $values;

            try {
                RequestRestResource::singleton()->updateByUserId($request->getParameter('userId'), $this->values);
                $this->getUser()->setFlash('notice', 'Request validated successfully.');

                if ($request->isXmlHttpRequest())
                    return true;
            } catch (YougoException $e) {
                $this->getUser()->setFlashError();
                if ($request->isXmlHttpRequest())
                    return false;
            }

            $this->redirect('requests/validation');
        }
    }

}
